import event, socket, gc, weakref

wd = {}

class Foo:
    def __init__(self, arg):
        self.arg = arg
        wd[arg] = weakref.ref(self)
        print '__init__', self.arg

    def __del__(self):
        print '__del__', self.arg

event.init()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setblocking(False)

def onRead(param):
    print 'onRead'
    print len(gc.get_referrers(s))
    s.close()

def onWrite(param):
    print 'onWrite'
    print len(gc.get_referrers(s))
    s.close()

print len(gc.get_referrers(s))
er = event.read(s.fileno(), onRead, Foo('read'))
ew = event.write(s.fileno(), onWrite, Foo('write'))
print dir(er)
print dir(ew)

print len(gc.get_referrers(s))

try:
    s.connect(('localhost', 80))
except:
    pass

r = gc.get_referrers
w = weakref.ref

print len(r(s))
event.dispatch()
print '---------------'
print r(r(s)[0])

ws = w(s)
del s
print r(ws())
print r(r(ws())[0])


gc.collect()
print gc.garbage

for i in wd.itervalues():
    print i(), len(r(i()))
    if len(r(i())) == 1:
        print r(r(i()))

print '-----------------'
ew.delete()
